from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.views import View
from .models import Post  # 导入 Post 模型
from django.contrib.auth.models import User  # 导入 User 模型

@method_decorator(csrf_exempt, name='dispatch')
class CreatePostView(View):
    """
    CreatePostView 视图类，用于处理创建动态的 POST 请求
    """

    def post(self, request):
        """
        处理 POST 请求，创建新动态
        :param request: HTTP 请求对象
        :return: JSON 响应
        """
        data = request.json().get('post', {})

        # 获取请求数据
        postid = data.get('postid')
        time = data.get('time')
        content = data.get('content')
        imgkey = data.get('imgkey')
        is_shared = data.get('isShared')
        shareid = data.get('shareid')

        # 验证请求数据
        if not all([postid, time, content, imgkey, is_shared, shareid]):
            return JsonResponse({"errno": 1, "success": False, "msg": "所有字段都是必填项"}, status=400)

        user = request.user  # 获取当前登录的用户
        if not user.is_authenticated:
            return JsonResponse({"errno": 1, "success": False, "msg": "用户未登录"}, status=401)

        # 创建新动态
        post = Post.objects.create(
            postid=postid,
            time=time,
            content=content,
            imgkey=imgkey,
            is_shared=is_shared,
            shareid=shareid,
            user=user
        )

        # 返回 JSON 响应
        return JsonResponse({"errno": 1, "success": True, "msg": "动态创建成功", "post": post.to_dict()}, status=201)
